<script setup lang="ts">
import { ref, reactive } from 'vue'
import { regYuanToFen, timeStamp } from '@/hooks/util'
import * as accountApi from '@/api/account'
import * as xyApi from '@/api/xy'
import * as fishApi from '@/api/fishGoods'
import { message } from 'ant-design-vue'
import SelectBox from './SelectBox.vue'

const myModal = ref()

const showModal = () => {
  getRobatList()
  getCinemaLineList()
  getityList()
  getIndustryList()
  myModal.value?.showModal()
}

defineExpose({
  showModal,
})

const emit = defineEmits<{
  refresh: []
}>()

// -----------------------------------------------------
// 拉取店铺列表
const robatList = ref([])
const getRobatList = async () => {
  const params = { currentPage: 1, pageSize: 100 }
  try {
    let { state, data, message: msg } = await accountApi.getFishRobotList(params)
    if (state === 200) {
      robatList.value = data.list.map(item => {
        return {
          label: item.nickName,
          value: item.id,
        }
      })
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 拉取院线列表
const cinemaLineList = ref([])
const getCinemaLineList = async () => {
  try {
    let { state, data, message: msg } = await xyApi.cinemaLineBrandList()
    if (state === 200) {
      cinemaLineList.value = data.map(item => {
        return {
          label: item.name,
          value: item.id,
        }
      })
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 拉取城市列表
const cityList = ref([])
const getityList = async () => {
  try {
    let {
      state,
      data,
      message: msg,
    } = await xyApi.cityList({
      classificationId: '',
    })
    if (state === 200) {
      cityList.value = data.map(item => {
        return {
          label: item.cityName,
          value: item.id,
        }
      })
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 获取行业
const getIndustryList = async () => {
  try {
    let { state, data, message: msg } = await fishApi.getSpBizType()
    if (state === 200) {
      industryList.value = data.map(item => {
        return {
          label: item.name,
          value: item.number,
        }
      })
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 获取类目
const getCategoryList = async (spBizTypeNum: string) => {
  try {
    let { state, data, message: msg } = await fishApi.getCategory({ spBizTypeNum })
    if (state === 200) {
      categoryList.value = data.map(item => {
        return {
          label: item.name,
          value: item.number,
        }
      })
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 获取渠道
const getChannelList = async (categoryNum: string) => {
  try {
    let { state, data, message: msg } = await fishApi.getChannel({ categoryNum })
    if (state === 200) {
      channelList.value = data.map(item => {
        return {
          label: item.name,
          value: item.number,
        }
      })
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

import type { SelectProps } from 'ant-design-vue'
// 行业名称
let spBizType = ref<string>('')
const industryList = ref<SelectProps['options']>([])
const selectIndustry = (selectValue: any) => {
  spBizType.value = selectValue as string
  getCategoryList(spBizType.value)
}

// 宝贝类目
let categoryId = ref<string>('')
const categoryList = ref<SelectProps['options']>([])
const selectCategory = (selectValue: any) => {
  categoryId.value = selectValue as string
  getChannelList(categoryId.value)
}

// 宝贝渠道
const channelList = ref<SelectProps['options']>([])

// -----------------------------------------------------

const formRef = ref()

const labelCol = {
  style: { width: '120px', textAlign: 'center' },
}
const wrapperCol = { span: 15 }

interface formState {
  cinemaLine?: string
  divisionId?: Array<string>
  day?: string
  timeStart?: string
  timeEnd?: string
  shopInterval?: string
  shopIntervalEnd?: string
  prodInterval?: string
  prodIntervalEnd?: string
  count?: string
  remark?: string
  originalPrice?: string
  sellPrice?: string
  postage?: string
  inventory?: string
  spBizType?: string
  categoryId?: string
  channelId?: string
}

const formState = ref<formState>({
  remark: '',
})

import type { Rule } from 'ant-design-vue/es/form'
// 金额的验证
import type { RuleObject } from 'ant-design-vue/es/form/interface'
let validateBalance = async (rule: RuleObject, value: string) => {
  value = String(value)
  if (value == null || value.trim() === '') {
    return Promise.reject('金额不能为空')
  }
  // 使用正则表达式来验证金额格式，允许整数和小数点后两位
  const regex = /^\d+(\.\d{1,2})?$/
  if (!regex.test(value)) {
    return Promise.reject('请输入有效的金额（整数或小数点后两位）')
  }
  // 将字符串转换为数字并检查是否大于0
  const amount = parseFloat(value)
  if (isNaN(amount) || amount <= 0) {
    return Promise.reject('请输入大于0的金额')
  }
  // 如果一切正常，返回成功
  return Promise.resolve()
}

let validatePostage = async (rule: RuleObject, value: string) => {
  value = String(value)
  if (value == null || value.trim() === '') {
    return Promise.reject('金额不能为空')
  }
  // 使用正则表达式来验证金额格式，允许整数和小数点后两位
  const regex = /^\d+(\.\d{1,2})?$/
  if (!regex.test(value)) {
    return Promise.reject('请输入有效的金额（整数或小数点后两位）')
  }
  // 如果一切正常，返回成功
  return Promise.resolve()
}

let inputValueRange = async (rule: RuleObject, value: string) => {
  value = String(value)
  if (value == null || value.trim() === '') {
    return Promise.reject('必须是 0 到 120 之间的整数')
  }

  const regex = /^\d+$/
  if (!regex.test(value)) {
    return Promise.reject('必须是 0 到 120 之间的整数')
  }

  const numberValue = parseInt(value, 10) // 使用基数10来确保是十进制转换
  // 检查数字是否在 [0, 120] 的整数范围内
  if (isNaN(numberValue) || numberValue < 0 || numberValue > 120) {
    return Promise.reject('必须是 0 到 120 之间的整数')
  }

  // 如果一切正常，返回成功
  return Promise.resolve()
}

const rules: Record<string, Rule[]> = {
  cinemaLine: [{ required: true, message: '请选择店铺', trigger: 'blur' }],
  divisionId: [{ required: true, message: '请选择地区', trigger: 'blur' }],
  day: [{ required: true, message: '请选择任务日期', trigger: 'blur' }],
  timeStart: [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
  timeEnd: [{ required: true, message: '请选择结束时间', trigger: 'blur' }],
  // shopInterval: [{ required: true, message: '请输入单店铺间隔区间', trigger: 'blur' }],
  shopInterval: [{ required: true, validator: inputValueRange, trigger: 'blur' }],
  shopIntervalEnd: [{ required: true, validator: inputValueRange, trigger: 'blur' }],
  // prodInterval: [{ required: true, message: '请输入单品间隔区间', trigger: 'blur' }],
  prodInterval: [{ required: true, validator: inputValueRange, trigger: 'blur' }],
  prodIntervalEnd: [{ required: true, validator: inputValueRange, trigger: 'blur' }],
  count: [{ required: true, message: '请输入店铺单日数量', trigger: 'blur' }],
  originalPrice: [{ required: true, validator: validateBalance, trigger: 'blur' }],
  sellPrice: [{ required: true, validator: validateBalance, trigger: 'blur' }],
  postage: [{ required: true, validator: validatePostage, trigger: 'blur' }],
  inventory: [{ required: true, message: '请输入库存个数', trigger: 'blur' }],
}

// 时间
// 将选择范围控制在7天
import type { Moment } from 'moment'
const dates = ref<Moment[]>([])
const onCalendarChange = (val: Moment[]) => {
  dates.value = val
}
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN'
import 'dayjs/locale/zh-cn'
import type { Dayjs } from 'dayjs'
type RangeValue = [Dayjs, Dayjs] | [string, string] | undefined
let startTime = ref<string>()
const changeTime = (e: RangeValue | [string, string], dataString: string) => {
  // console.log('选择日期=', dataString)
  startTime.value = dataString
}

// 选择时间
let errorMessage = ref('')

const checkTime1 = () => {
  // 将时间字符串转换为Date对象进行比较
  const startTime = new Date(`1970-01-01T${formState.value.timeStart}`)
  const endTime = new Date(`1970-01-01T${formState.value.timeEnd}`)

  if (endTime < startTime) {
    formState.value.timeEnd = ''
    // formState.value.timeStart = ""

    // errorMessage.value = '结束时间必须晚于开始时间';
    message.error('结束时间必须晚于开始时间~')
  } else {
    // errorMessage.value = '';
  }
}
const checkTime2 = () => {
  // 将时间字符串转换为Date对象进行比较
  const startTime = new Date(`1970-01-01T${formState.value.timeStart}`)
  const endTime = new Date(`1970-01-01T${formState.value.timeEnd}`)

  if (startTime > endTime) {
    // formState.value.timeEnd = ""
    formState.value.timeStart = ''

    // errorMessage.value = '结束时间必须晚于开始时间';
    message.error('结束时间必须晚于开始时间~')
  } else {
    // errorMessage.value = '';
  }
}
// 步骤条
let current = ref(0)
const steps = [
  {
    title: '店铺',
    content: '1',
  },
  {
    title: '院线',
    content: '2',
  },
  {
    title: '城市',
    content: '3',
  },
  {
    title: '间隔',
    content: '4',
  },
  {
    title: '宝贝属性',
    content: '5',
  },
]

const next = () => {
  if (current.value == 3) {
    if (Number(formState.value.shopInterval) > Number(formState.value.shopIntervalEnd)) {
      message.error('单店铺间隔区间的结束时间需要大于开始时间~')
      return
    }
    if (Number(formState.value.prodInterval) > Number(formState.value.prodIntervalEnd)) {
      message.error('单品间隔区间的结束时间需要大于开始时间~')
      return
    }
  }
  current.value++
}

let okShopList = reactive<Array<any>>([])
const getShop = (e: any) => {
  // console.log('选中的店铺=', e)
  okShopList = [...e]
}

let okCinemaList = reactive<Array<any>>([])
const getCinemaLine = (e: any) => {
  // console.log('选中的院线=', e)
  okCinemaList = [...e]
}

let okCityList = reactive<Array<any>>([])
const getCity = (e: any) => {
  // console.log('选中的城市=', e)
  okCityList = [...e]
}

const submit = () => {
  // console.log('okShopList=', okShopList)
  // console.log('okCinemaList=', okCinemaList)
  // console.log('okCityList=', okCityList)

  let relList = []
  okShopList.map(item => {
    relList.push({
      name: item.label,
      number: item.value,
      type: 1,
    })
  })
  okCinemaList.map(item => {
    relList.push({
      name: item.label,
      number: item.value,
      type: 2,
    })
  })
  okCityList.map(item => {
    relList.push({
      name: item.label,
      number: item.value,
      type: 3,
    })
  })

  // console.log('relList=', relList)

  formRef.value.validate().then(async () => {
    // console.log('formState=', formState.value)

    const params = {
      spBizType: formState.value.spBizType,
      categoryId: formState.value.categoryId,
      channelId: formState.value.channelId,
      originalPrice: regYuanToFen(formState.value.originalPrice as string, 100),
      sellingPrice: regYuanToFen(formState.value.sellPrice as string, 100),
      transportFee: regYuanToFen(formState.value.postage as string, 100),
      inventory: formState.value.inventory,
      putawayIntervalBeginTime: formState.value.prodInterval, // 上品间隔开始时间
      putawayIntervalEndTime: formState.value.prodIntervalEnd,
      robotDayPutawayCount: formState.value.count, // 机器人每天上品数量
      robotIntervalBeginTime: formState.value.shopInterval, // 机器人间隔开始时间
      robotIntervalEndTime: formState.value.shopIntervalEnd,
      startState: 1, // 启动状态
      remark: formState.value.remark,

      taskExecuteTime: timeStamp(startTime.value), // 日期
      taskBeginTime: formState.value.timeStart, // 开始时间
      taskEndTime: formState.value.timeEnd, // 结束时间

      relList,
    }

    // console.log('params-', params)

    try {
      let { state, message: msg } = await xyApi.addAutomatePutaway(params)
      if (state === 200) {
        message.success('添加成功')
        emit('refresh')
        myModal.value?.cancelModal()
      } else {
        message.error(msg)
      }
    } catch (error) {
      message.error('网络请求连接失败~')
    }
  })
}
</script>

<template>
  <MyModal ref="myModal" title="添加任务" :top="25" :width="1000">
    <template #content>
      <div>
        <a-form
          ref="formRef"
          :rules="rules"
          :model="formState"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-steps :current="current">
            <a-step v-for="item in steps" :key="item.title" :title="item.title" />
          </a-steps>

          <div v-show="steps[current].content == '1'">
            <SelectBox
              v-if="robatList.length > 0"
              :yesList="robatList"
              @send-list="getShop"
            ></SelectBox>
          </div>

          <div v-show="steps[current].content == '2'">
            <SelectBox
              v-if="cinemaLineList.length > 0"
              :yesList="cinemaLineList"
              @send-list="getCinemaLine"
            ></SelectBox>
          </div>

          <div v-show="steps[current].content == '3'">
            <SelectBox
              v-if="cityList.length > 0"
              :yesList="cityList"
              @send-list="getCity"
            ></SelectBox>
          </div>

          <div v-show="steps[current].content == '4'" class="step">
            <a-form-item label="任务日期" name="day" style="width: 600px">
              <a-date-picker
                style="width: 365px"
                v-model:value="formState.day"
                @calendarChange="onCalendarChange"
                :locale="locale"
                placeholder="请选择日期"
                @change="changeTime"
              />
            </a-form-item>

            <div style="display: flex">
              <a-form-item label="开始时间" name="timeStart">
                <a-time-picker
                  placeholder="请选择时间"
                  v-model:value="formState.timeStart"
                  valueFormat="HH:mm:ss"
                  style="width: 120px"
                  @change="checkTime1"
                />
              </a-form-item>
              <a-form-item label="结束时间" name="timeEnd">
                <a-time-picker
                  placeholder="请选择时间"
                  v-model:value="formState.timeEnd"
                  valueFormat="HH:mm:ss"
                  style="width: 120px"
                  @change="checkTime2"
                />
              </a-form-item>
            </div>
            <div style="display: flex">
              <a-form-item label="单店铺间隔区间" name="shopInterval">
                <a-input
                  style="width: 170px"
                  v-model:value="formState.shopInterval"
                  suffix="分钟"
                ></a-input>
                <span style="margin: 0 10px">-</span>
              </a-form-item>

              <a-form-item name="shopIntervalEnd" style="width: 280px">
                <a-input
                  style="width: 170px"
                  v-model:value="formState.shopIntervalEnd"
                  suffix="分钟"
                ></a-input>
              </a-form-item>
            </div>

            <div style="display: flex">
              <a-form-item label="单品间隔区间" name="prodInterval">
                <a-input
                  style="width: 170px"
                  v-model:value="formState.prodInterval"
                  suffix="分钟"
                ></a-input>
                <span style="margin: 0 10px">-</span>
              </a-form-item>

              <a-form-item name="prodIntervalEnd" style="width: 280px">
                <a-input
                  style="width: 170px"
                  v-model:value="formState.prodIntervalEnd"
                  suffix="分钟"
                ></a-input>
              </a-form-item>
            </div>

            <a-form-item label="店铺单日数量" name="count">
              <a-input style="width: 365px" v-model:value="formState.count" suffix="个"></a-input>
            </a-form-item>

            <a-form-item label="备注" name="remark">
              <a-input style="width: 365px" v-model:value="formState.remark"></a-input>
            </a-form-item>
          </div>

          <div v-show="steps[current].content == '5'" class="step" style="margin-right: 100px">
            <a-form-item label="行业名称" name="spBizType">
              <a-select
                v-model:value="formState.spBizType"
                @change="selectIndustry"
                placeholder="行业名称"
              >
                <a-select-option
                  v-for="(item, index) in industryList"
                  :key="index"
                  :value="item.value"
                >
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="宝贝类目" name="categoryId">
              <a-select
                v-model:value="formState.categoryId"
                @change="selectCategory"
                placeholder="宝贝类目"
              >
                <a-select-option
                  v-for="(item, index) in categoryList"
                  :key="index"
                  :value="item.value"
                >
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="宝贝渠道" name="channelId">
              <a-select v-model:value="formState.channelId" placeholder="宝贝渠道">
                <a-select-option
                  v-for="(item, index) in channelList"
                  :key="index"
                  :value="item.value"
                >
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="原价" name="originalPrice">
              <a-input
                type="number"
                style="width: 375px"
                v-model:value="formState.originalPrice"
                suffix="元"
              ></a-input>
            </a-form-item>

            <a-form-item label="售价" name="sellPrice">
              <a-input
                type="number"
                style="width: 375px"
                v-model:value="formState.sellPrice"
                suffix="元"
              ></a-input>
            </a-form-item>

            <a-form-item label="邮费" name="postage">
              <a-input
                type="number"
                style="width: 375px"
                v-model:value="formState.postage"
                suffix="元"
              ></a-input>
            </a-form-item>

            <a-form-item label="库存" name="inventory">
              <template #help>如您店铺未开通鱼小铺，只能设置库存为1，否则会上品失败</template>
              <a-input
                type="number"
                style="width: 375px"
                v-model:value="formState.inventory"
                suffix="个"
              ></a-input>
            </a-form-item>
          </div>

          <div>
            <a-button v-if="current < steps.length - 1" type="primary" @click="next">
              下一步
            </a-button>
            <a-button v-if="current == steps.length - 1" type="primary" @click="submit">
              完成
            </a-button>
            <a-button v-if="current > 0" style="margin-left: 8px" @click="() => current--">
              上一步
            </a-button>
          </div>
        </a-form>
      </div>
    </template>
  </MyModal>
</template>

<style scoped lang="less">
.step {
  display: grid;
  justify-content: center;
  align-content: center;
  height: 380px;
  margin-top: 30px;
}
</style>
